/**
 * 通过主键获取
 * @param {*} modelName
 * @param {*} id
 * @param {*} cb
 */
module.exports.getByPrimary = function (modelName, id, cb) {
  database.models[modelName].get(id, cb);
};

/**
 * 获取一条数据
 * @param {*} modelName
 * @param {*} conditions
 * @param {*} cb
 */
module.exports.findOne = function (modelName, conditions, cb) {
  const Model = database.models[modelName];
  if (!Model) return cb(null, "模型不存在");
  if (!conditions) return cb(null, "条件为空");
  Model.one(conditions, function (err, target) {
    if (err) return cb("查询失败" + err);
    return cb(null, target);
  });
};

/**
 * 新增对象
 * @param {*} modelName 模型名称
 * @param {*} source 对象数据
 * @param {*} cb
 */
module.exports.create = function (modelName, source, cb) {
  const Model = database.models[modelName];
  if (!Model) return cb(null, "模型不存在");
  Model.create(source, cb);
};

/**
 * 查询列表
 * @param {*} modelName
 * @param {*} conditions
 * {
 *      columns: {
 *          字段名：条件值
 *      },
 *      offset: "偏移",
 *      omit: [字段, ...],
 *      only: [需要字段, ...],
 *      limit: 数量,
 *      order: [字段, ...]
 * }
 * @param {*} cb
 */
module.exports.list = function (modelName, conditions, cb) {
  let Model = database.models[modelName];
  if (!Model) return cb(null, "模型不存在");
  if (conditions) {
    const { columns, offset, limit, only, omit, order } = conditions;

    if (columns) {
      Model = Model.find(columns);
    } else {
      Model = Model.find();
    }

    if (offset) {
      Model = Model.offset(parseInt(offset));
    }

    if (limit) {
      Model = Model.limit(parseInt(limit));
    }

    if (only) {
      Model = Model.only(only);
    }

    if (omit) {
      Model = Model.omit(omit);
    }

    if (order) {
      Model = Model.order(order);
    }
  } else {
    Model = Model.find();
  }

  Model.run(function (err, models) {
    if (err) return cb(null, "查询失败" + err);
    cb(null, models);
  });
};

/**
 * 根据主键删除条目
 * @param {*} modelName
 * @param {*} id
 * @param {*} cb
 */
module.exports.delete = function (modelName, id, cb) {
  const Model = database.models[modelName];
  if (!Model) return cb(null, "模型不存在");
  Model.get(id, function (err, obj) {
    if (err) return cb(err);
    obj.remove(null, cb);
  });
};
